// userId: 用户登陆时获取到的
// roomId: 当前这局游戏的房间号. 通过匹配结果获取到
// isWhite: 当前这局游戏是否是白子. 通过匹配结果获取到
// 这三个属性包裹到一个 gameInfo 对象中
let gameInfo = {
    roomId: null,
    thisUserId: null,// 我方玩家
    thatUserId: null,// 对方玩家
    isWhite: false,// 先手
    whiteUser: 0,
    isWatch: false// 当前是否为观战
}
var chess = document.getElementById('chess');
var context = chess.getContext('2d');
var chessBoard = [];//棋盘初始化
//////////////////////////////////////////////////
// 设定界面显示相关操作
//////////////////////////////////////////////////
function setScreenText(me) {
    let prompt = document.querySelector("#prompt");
    if (gameInfo.isWatch){
        prompt.innerHTML = "观战中..."
    }else {
        if (me) {
            prompt.innerHTML = "轮到你落子了!"
        } else {
            prompt.innerHTML = "轮到对方落子了!"
        }
    }
}

//////////////////////////////////////////////////
// 初始化游戏的 webSocket
//////////////////////////////////////////////////
let gameurl = 'ws://'+ location.host +'/game';
let websocket = new WebSocket(gameurl);
websocket.onopen = function () {
}
websocket.onclose = function () {
    console.log("离开房间")
}
websocket.onerror = function () {
    console.log("连接异常")
}
window.onbeforeunload = function(){
    websocket.close()
    chatWebsocket.close()
}
websocket.onmessage = function (e) {
    console.log('收到消息: ' + e.data);
    let response = JSON.parse(e.data);
    if(response.message == 'repeatConnection'){
        alert('该账号已在别地登录! 如非本人操作, 请及时检查帐号邮箱绑定并修改密码')
        window.location.href = 'login.html'
        return;
    }
    // 是我下还是对方下. 根据服务器分配的先后手情况决定
    var me = gameInfo.isWhite;
    // 游戏是否结束
    var over = false;
    //初始化 chessBord数组(表示棋盘的数组)
    for (var i = 0; i < 15; i++) {
        chessBoard[i] = [];
        for (var j = 0; j < 15; j++) {
            chessBoard[i][j] = 0;
        }
    }
    context.strokeStyle = "#BFBFBF";
    // 背景图片
    var logo = new Image();
    logo.src = "./images/bg6.jpg";
    logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        initChessBoard();
        if (response.message == 'watch'){
            // 隐藏右侧对话框
            let chat = document.querySelector("div.chat");
            chat.style.display = 'none'
            // 是观战的用户   ---     初始化棋盘
            gameInfo.isWatch = true;
            let board = response.board;
            gameInfo.whiteUser = response.whiteUser;// 当前棋局的先手
            // 当前棋局
            for(var i = 0; i < board.length; i++){
                for(var j = 0; j < board[0].length; j++){
                    if(board[i][j] != 0){
                        chessBoard[i][j] = 1;
                        oneStep(j, i, board[i][j] == gameInfo.whiteUser);
                    }
                }
            }
            setScreenText(true)
        }else if (response.message == 'gameReady'){
            if (!response.ok){
                console.log('游戏连接失败!  ' + response.reason)
                window.location.href = 'index.html'
                return;
            }
            gameInfo.roomId = response.roomId;
            gameInfo.thisUserId = response.thisUserId;
            gameInfo.thatUserId = response.thatUserId;
            gameInfo.isWhite = (response.thisUserId == response.whiteUser)
            me = response.thisUserId == response.whiteUser
            // 开局是我方下棋, 显示定时器
            if (me && !gameInfo.isWatch){
                timer();
            }

            console.log(gameInfo)
            // 初始化棋盘
            chess.onclick = function (e) {
                if (over) {// 游戏结束
                    return;
                }
                if (!me) {// 不是我方落棋
                    return;
                }
                var x = e.offsetX;// 拿到落棋的横纵坐标
                var y = e.offsetY;
                // 每个格子 30px
                var col = Math.floor(x / 30);
                var row = Math.floor(y / 30);
                if (chessBoard[row][col] == 0) {
                    // 新增发送数据给服务器的逻辑
                    send(row, col);
                }
            }
            function send(row, col) {
                let request = {
                    message: 'putChess',
                    userId: gameInfo.thisUserId,
                    row: row,
                    col: col
                };
                websocket.send(JSON.stringify(request))
                stopTimer()
            }
            // 设置显示区域内容
            setScreenText(gameInfo.isWhite)
        }
        websocket.onmessage = function (e) {
            console.log(e.data)
            let response = JSON.parse(e.data);
            if (response.message != 'putChess'){
                console.log("响应类型错误")
                return;
            }
            if (gameInfo.isWatch == true){
                // 是在观战
                oneStep(response.col, response.row, gameInfo.whiteUser == response.userId)
            }else {

                if (response.userId == gameInfo.thisUserId){
                    // 是我方落子    ---     绘制棋子
                    oneStep(response.col, response.row, gameInfo.isWhite)
                }else if (response.userId == gameInfo.thatUserId){
                    // 是对方落子   ---     绘制棋子
                    oneStep(response.col, response.row, !gameInfo.isWhite)
                }else {
                    console.log("响应的userId错误")
                    return;
                }
            }
            // 设置当前二位数组的值
            chessBoard[response.row][response.col] = 1;

            // 交换双方的落棋轮次
            me = !me
            // 轮到我方下棋了, 显示定时器
            if (me && !gameInfo.isWatch){
                timer();
            }
            setScreenText(me);

            // 游戏是否结束
            if (response.winner != 0){
                stopTimer()
                let prompt = document.querySelector("#prompt")
                if (gameInfo.isWatch){
                    if (gameInfo.whiteUser == response.winner){
                        prompt.innerHTML = '白子获胜!'
                    }else {
                        prompt.innerHTML = '黑子获胜!'
                    }
                }else {
                    if (response.winner == gameInfo.thisUserId){
                        // 我方获胜
                        if(response.reason == 'dropped'){
                            prompt.innerHTML = '对方掉线! 恭喜你赢了!'
                        }else {
                            prompt.innerHTML = '恭喜你赢了!'
                        }
                    }else if(response.winner == gameInfo.thatUserId){
                        // 对方获胜
                        prompt.innerHTML = '很遗憾你输了!'
                    }else{
                        alert('字段错误')
                    }
                }
                // 玩家点击退回大厅
                let backBtn = document.createElement('button');
                backBtn.innerHTML = '回到游戏大厅'
                backBtn.className = 'back'
                backBtn.style.color = 'red'
                let all = document.querySelector("div.all");
                all.appendChild(backBtn)
                backBtn.onclick = function(){
                    window.location.href = 'index.html'
                }
            }
        }
    }
}

//////////////////////////////////////////////////
// 初始化聊天的 webSocket
//////////////////////////////////////////////////
let chaturl = "ws://" + location.host + "//chat";
let chatWebsocket = new WebSocket(chaturl);
chatWebsocket.onopen = function () {
    console.log("进入房间")
}
chatWebsocket.onclose = function () {
    console.log("离开房间")
}
chatWebsocket.onerror = function () {
    console.log("连接异常")
}
chatWebsocket.onmessage = function (e) {
    console.log('收到消息: ' + e.data);
    let response = JSON.parse(e.data);

    if (response.state == 'FAIL'){
        if (response.reason == 'notlogin'){
            console.log('游戏连接失败!  ' + response.reason)
            window.location.href = 'index.html'
            return;
        }else if (response.reason == 'outline'){
            alert('对方离线')
        }else {
            console.log("收到错误的消息响应")
        }
    }
    // 解析消息

    let nickname = document.createElement('div');
    nickname.innerHTML = response.nickname;
    let message = document.createElement('div');
    message.innerHTML = response.message;
    message.className = 'message'

    let msgdiv = document.createElement('div')
    if (response.userId == gameInfo.thisUserId){
        // 该消息是我方发的
       msgdiv.className = 'me'
    }else {
        msgdiv.className = 'you'
    }
    msgdiv.appendChild(nickname)
    msgdiv.appendChild(message)

    let messages = document.querySelector("div.messages")
    messages.appendChild(msgdiv)
    messages.scrollTop = messages.scrollHeight
}
// 点击发送消息
let putmsg = document.querySelector("button.submit")
putmsg.onclick = function () {
    let content = document.querySelector(".textarea");
    chatWebsocket.send(JSON.stringify({
        message: content.value
    }))
    content.value = ''
}

// 绘制棋盘网格
function initChessBoard() {
    context.strokeStyle = "rga(255,255,255)";
    for (var i = 0; i < 15; i++) {
        context.moveTo(15 + i * 30, 15);
        context.lineTo(15 + i * 30, 430);
        context.stroke();
        context.moveTo(15, 15 + i * 30);
        context.lineTo(435, 15 + i * 30);
        context.stroke();
    }
}
// 绘制一个棋子, me 为 true
// i 表示列, j 表示行
function oneStep(i, j, isWhite) {
    context.beginPath();
    context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
    context.closePath();// 画出一个圆形
    var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
    if (!isWhite) {
        gradient.addColorStop(0, "#0A0A0A");
        gradient.addColorStop(1, "#636766");
    } else {
        gradient.addColorStop(0, "#D1D1D1");
        gradient.addColorStop(1, "#F9F9F9");
    }
    context.fillStyle = gradient;
    context.fill();
}

// 定时器
var myTimer;
function timer() {
    //点击后定时器事件开始
    let timerdiv = document.querySelector(".timer");
    timerdiv.innerHTML = '15'
    timerdiv.style.border = '5px solid whitesmoke'
    myTimer = window.setInterval(function() {
        timerdiv.innerHTML--;
        //当数值为 0时，停止定时器
        if (timerdiv.innerHTML == 0) {
            timerdiv.innerHTML = ''
            timerdiv.style.border = ''
            window.clearInterval(myTimer);
            // 随机选取一颗可以下的地方下
            while (true){
                var i = Math.floor(Math.random()*15)
                var j = Math.floor(Math.random()*15)
                if(chessBoard[i][j] == 0){
                    let request = {
                        message: 'putChess',
                        userId: gameInfo.thisUserId,
                        row: j,
                        col: i
                    };
                    websocket.send(JSON.stringify(request))
                    return
                }
            }
        }
    }, 1000);
}
function stopTimer() {
    let timerdiv = document.querySelector(".timer");
    timerdiv.innerHTML = ''
    timerdiv.style.border = ''
    window.clearInterval(myTimer);
}